package by.grsu.vashchilo.dao.impl;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import by.grsu.vashchilo.dao.impl.AbstractDao;
import by.grsu.vashchilo.entity.TicketItem;
import by.grsu.vashchilo.table.TicketItemTable;

public class TicketItemDao extends AbstractDao<TicketItemTable, TicketItem> {
	public TicketItemDao(String rootFolderPath) {
		super(rootFolderPath);
	}

	@Override
	public void saveNew(TicketItem newTicket) {
		newTicket.setId(getNextId());
		final TicketItemTable ticketItemTable = deserializeFromXml();
		ticketItemTable.getRows().add(newTicket);
		serializeToXml(ticketItemTable);

	}

	@Override
	public void update(TicketItem entity) {
		final TicketItemTable ticketItemTable = deserializeFromXml();
		for (TicketItem b : ticketItemTable.getRows()) {
			if (b.getId().equals(entity.getId())) {
				b.setOrderType(entity.getOrderType());
				b.setOwnerId(entity.getOwnerId());
				b.setTicketid(entity.getTicketid());
			}
		}
		serializeToXml(ticketItemTable);
	}

	@Override
	public TicketItem get(Serializable id) {
		final TicketItemTable ticketItemTable = deserializeFromXml();
		for (TicketItem b : ticketItemTable.getRows()) {
			if (b.getId().equals(id)) {
				return b;
			}
		}
		return null;
	}

	@Override
	public List<TicketItem> getAll() {
		TicketItemTable ticketItemTable = deserializeFromXml();
		return ticketItemTable.getRows();
	}

	@Override
	public void delete(Serializable id) {
		final TicketItemTable ticketItemTable = deserializeFromXml();
		TicketItem toBeDeletedTicket = null;
		for (TicketItem b : ticketItemTable.getRows()) {
			if (b.getId().equals(id)) {
				toBeDeletedTicket = b;
			}
		}
		ticketItemTable.getRows().remove(toBeDeletedTicket);
		serializeToXml(ticketItemTable);
	}

	@Override
	protected Class<TicketItemTable> getTableClass() {
		return TicketItemTable.class;
	}

}
